<script lang="ts" setup>
  import { onMounted, reactive, ref, computed } from 'vue'
  import userService from '@/api/userService'
  import resconfig from '@/api/userService'
  import { useRouter } from 'vue-router'
  import appStore from '@/store'
  import { timeFormatUTC } from '@/utils/formatter'
  import { ElMessageBox, ElMessage, FormRules, FormInstance } from 'element-plus'
  import userType from '@/tips/userType.json'
  import activation from '@/tips/activation.json'
  const userTypeData: { [key: string]: string } = reactive(userType)
  const activationData: { [key: string]: string } = reactive(activation)
  interface apiData {
    userName: 'string'
    email: 'string'
    phone: 'string'
    last_login: 'string'
    activation: 'number'
    user_type: 'string'
    id?: 'string'
    isEdit?: boolean
  }
  let tableData: apiData[] = reactive([])
  const router = useRouter()
  const bulidUser = () => {
    router.push({ name: 'adduser' })
  }

  const activation_options = [
    {
      value: 0,
      label: '未激活'
    },
    {
      value: 1,
      label: '激活'
    },
    {
      value: -1,
      label: '冻结'
    }
  ]
  const userData = reactive({
    project_id: appStore.userStore.project_id,
    offset: 1,
    limit: 10
  })
  const toInsert = (id: string, name: string) => {
    localStorage.setItem(
      'insertData',
      JSON.stringify({
        id,
        name
      })
    )
    router.push({ name: 'insert' })
  }
  const buildInsertResourceConfig = (id: string, name: string) => {
    localStorage.setItem(
      'insertData',
      JSON.stringify({
        id,
        name
      })
    )
    router.push({ name: 'insertResourceConfig' })
  }
  const escalation = async (id: any, name: any, UserType: any) => {
    ElMessageBox.confirm(`当前用户将提升为普通管理员？\n用户名: ${name}\nID: ${id}`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    })
      .then(async () => {
        let res = await userService.escalationPrivileges(id)
        if (res.status == 200) {
          ElMessage({
            type: 'success',
            message: '升级成功'
          })
          getResconfig()
        } else {
          ElMessage({
            type: 'info',
            message: '升级失败'
          })
        }
      })
      .catch(() => {})
  }
  let tableTotal = ref(0)
  const getResconfig = async () => {
    let res = await userService.getAlluserinfo(userData)
    if (res.data.users) {
      res.data.users.forEach((item: any) => {
        item.isEdit = false
      })
      tableTotal.value = res.data.total
      tableData.length = 0
      tableData.push(...res.data.users)
    }
  }
  const dialogVisible = ref(false)
  const dialogId = ref()
  const buildTenant = async (id: any) => {
    dialogVisible.value = true
    dialogId.value = id
  }
  const deleteUser = (id: any, name: any) => {
    ElMessageBox.confirm(`确认删除此条数据？\n用户名: ${name}\n用户ID: ${id}`, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        let res = await userService.delUser(id)
        if (res.status < 300) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          getResconfig()
        } else {
          ElMessage({
            type: 'info',
            message: '删除失败'
          })
        }
      })
      .catch(() => {})
  }
  const changeUser = (row: any) => {
    tableData.forEach((item) => {
      if (item.id != row.id) {
        item.isEdit = false
      }
    })
    row.isEdit = true
  }
  const closeRow = async (row: any) => {
    await getResconfig()
    row.isEdit = false
  }
  const param = reactive({
    resconfig: {
      phone: '',
      email: ''
    }
  })
  const onSubmit = async (row: any) => {
    param.resconfig = JSON.parse(JSON.stringify(row))
    let phone = new RegExp(/^(1[2-9][0-9])\d{8}$/)
    let email = new RegExp(/^\w+@\w+(\.\w+)+$/)
    if (param.resconfig.phone) {
      let result = phone.test(param.resconfig.phone)
      if (!result) {
        ElMessage({
          message: '请填写正确的电话号码',
          type: 'warning'
        })
        return false
      }
    }
    if (param.resconfig.email) {
      let result = email.test(param.resconfig.email)
      if (!result) {
        ElMessage({
          message: '请填写正确的邮箱',
          type: 'warning'
        })
        return false
      }
      if (!result) return false
    }

    try {
      let res = await userService.changeUser(param)
      if (res.status < 300) {
        ElMessage({
          message: '修改成功',
          type: 'success'
        })
        getResconfig()
      }
    } catch (err) {
      ElMessage.error('修改失败')
    }
  }
  const reset = async (id: any) => {
    ElMessageBox.confirm('确认重置此用户密码？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        let res = await userService.resetPassWord(id)
        if (res.status < 300) {
          ElMessage({
            type: 'success',
            message: '重置成功'
          })
        } else {
          ElMessage({
            type: 'info',
            message: '重置失败'
          })
        }
      })
      .catch(() => {})
  }

  getResconfig()
  if (appStore.userStore.UserType === 0) {
    router.push({ name: 'Homepage' })
  }
  const rules = reactive<FormRules>({
    ori_project_id: [{ required: true, message: '请输入新增租户名称', trigger: 'blur' }],
    domain_name: [{ required: true, message: '请输入绑定租户标识', trigger: 'blur' }]
  })
  let insertData = ref({} as { [key: string]: string })
  let irData = reactive({
    data: {
      ori_project_id: '',
      domain_name: '',
      user_id: ''
    }
  } as { [key: string]: { [key: string]: string } })
  const bindResConf = reactive({
    data: {
      ori_project_id: '',
      domain_name: '',
      user_id: ''
    }
  })
  const small = ref(false)
  const disabled = ref(false)
  const background = ref(true)
  const handleSizeChange = (val: number) => {
    userData.limit = val
    userData.offset = 1
    getResconfig()
  }
  const handleCurrentChange = (val: number) => {
    userData.offset = val
    getResconfig()
  }
  const assRef = ref<FormInstance>()
  const newTenant = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        bindResConf.data = JSON.parse(JSON.stringify(irData.data))
        bindResConf.data['user_id'] = dialogId.value
        try {
          let res = await resconfig.buildResconfig(bindResConf.data)
          if (res.status < 300) {
            ElMessage({
              message: '绑定成功',
              type: 'success'
            })
            getResconfig()
            dialogVisible.value = false
          }
        } catch (err) {
          ElMessage.error('绑定失败')
        }
      }
    })
  }
</script>
<template>
  <div id="user-info" class="list-index">
    <div class="run-box">
      <div class="state-box">
        <div class="run-label">用户管理</div>
      </div>
    </div>
    <div class="insert-info">
      <div class="insert-top">
        <button class="btn new" @click="bulidUser">新增用户</button>
      </div>
      <div class="insert-table">
        <el-table
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{ background: '#fafafe', color: '#1d1d1f' }"
          :border="true"
          :default-sort="{ prop: 'LastLogin', order: 'descending' }"
        >
          <el-table-column label="用户名">
            <template #default="scope">
              <div class="toDetails" @click="toInsert(scope.row.id, scope.row.username)">
                {{ scope.row.username }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="用户类型">
            <template #default="scope">
              <div class="id-box">
                {{ userTypeData[`${scope.row.user_type}`] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="激活状态">
            <template #default="scope">
              <div class="id-box" v-if="!scope.row.isEdit">
                {{ activationData[`${scope.row.activation}`] }}
              </div>
              <div class="change" v-else>
                <el-select v-model="scope.row.activation" class="m-2" placeholder="请选择激活状态">
                  <el-option v-for="item in activation_options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="电话">
            <template #default="scope">
              <div class="id-box" v-if="!scope.row.isEdit">
                {{ scope.row.phone }}
              </div>
              <div class="change" v-else>
                <el-input v-model="scope.row.phone" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="邮箱" show-overflow-tooltip>
            <template #default="scope">
              <div class="id-box" v-if="!scope.row.isEdit">
                {{ scope.row.email }}
              </div>
              <div class="change" v-else>
                <el-input type="email" v-model="scope.row.email" maxlength="1024" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="total_res_number" label="使用租户数量" />
          <el-table-column prop="last_login" label="最近登录" :formatter="timeFormatUTC" width="280" sortable />
          <el-table-column fixed="right" label="操作" width="470" v-if="appStore.userStore.UserType === 9">
            <template #default="scope">
              <div v-if="!scope.row.isEdit" class="actions-box">
                <div class="actions-details" @click="reset(scope.row.id)">重置密码</div>
                <div class="line"></div>
                <div class="actions-details" @click="changeUser(scope.row)">修改</div>
                <div class="line"></div>
                <div class="actions-delete" @click="deleteUser(scope.row.id, scope.row.username)">删除</div>
                <div class="line"></div>
                <div class="actions-delete" @click="buildInsertResourceConfig(scope.row.id, scope.row.username)">新建租户</div>
                <div class="line"></div>
                <div class="actions-delete" @click="buildTenant(scope.row.id)">绑定已有租户</div>
                <div class="line" v-if="scope.row.user_type < 5"></div>
                <div class="actions-delete" v-if="scope.row.user_type < 5" @click="escalation(scope.row.id, scope.row.username, scope.row.user_type)">
                  升级权限
                </div>
              </div>
              <div v-else class="actions-box">
                <div class="actions-details" @click="onSubmit(scope.row)">保存</div>
                <div class="line"></div>
                <div class="actions-details" @click="closeRow(scope.row)">取消</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="userData.offset"
          v-model:page-size="userData.limit"
          :page-sizes="[10, 20, 50, 100]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
      <!-- 新增租户弹框 -->
      <el-dialog title="绑定已有租户" v-model="dialogVisible" width="550px" center>
        <el-form ref="assRef" :model="irData.data">
          <el-form-item prop="domain_name" :rules="rules.domain_name">
            <template #label>
              <div class="item-label">新增租户名称</div>
            </template>
            <el-input type="text" v-model="irData.data.domain_name"></el-input>
          </el-form-item>
          <el-form-item prop="ori_project_id" :rules="rules.ori_project_id">
            <template #label>
              <div class="item-label">绑定租户标识</div>
            </template>
            <el-input type="text" v-model="irData.data.ori_project_id"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="newTenant(assRef)">确定</el-button>
            </span>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  @import '@/assets/scss/list.scss';
  #user-info {
    .insert-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      .insert-title {
        font-size: 14px;
        font-weight: bold;
      }
      .btn {
        width: 100px;
        height: 30px;
      }
    }
    .el-form-item {
      margin-bottom: 24px;
    }
  }
</style>
